package com.paomi.client.activity.detail;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paomi.client.R;
import com.paomi.client.activity.detail.adapter.OrderDetailAdapter;
import com.paomi.client.activity.detail.model.OrderDeatilBean;
import com.paomi.client.activity.detail.model.SendDetailBean;
import com.paomi.client.activity.detail.presenter.OrderDetailPre;
import com.paomi.client.activity.pay.model.AddressBean;
import com.paomi.client.activity.payResult.ResultPayActivity;
import com.paomi.client.base.BaseMvpActivity;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.bean.DictBean;
import com.paomi.client.bean.SetBeanPay;
import com.paomi.client.fragment.order.model.OrderListBean;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.utils.Util;
import com.paomi.client.widget.RxToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailActivity extends BaseMvpActivity<OrderDetailView, OrderDetailPre> implements OrderDetailView {
    @BindView(R.id.tv_default)
    TextView tv_default;
    OrderDetailAdapter adapter;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    List<OrderListBean.OrderGoods> list = new ArrayList<>();//票务列表
    @BindView(R.id.detail_iv)
    ImageView detail_iv;
    @BindView(R.id.order_state)
    TextView orderState;
    @BindView(R.id.order_time)
    TextView orderTime;
    @BindView(R.id.order_name)
    TextView orderName;
    @BindView(R.id.order_phone)
    TextView orderPhone;
    @BindView(R.id.order_address)
    TextView orderAddress;
    @BindView(R.id.total_tv)
    TextView totalTv;
    @BindView(R.id.pass_tv)
    TextView passTv;
    @BindView(R.id.lay_coupon)
    LinearLayout lay_coupon;//优惠券布局
    @BindView(R.id.lay_send)
    LinearLayout lay_send;//快递费布局
    @BindView(R.id.coupon_tv)
    TextView couponTv;
    @BindView(R.id.belly_tv)
    TextView bellyTv;
    @BindView(R.id.express_tv)
    TextView expressTv;
    @BindView(R.id.tv_allmoney)
    TextView tvAllmoney;
    @BindView(R.id.tv_orderid)
    TextView tvOrderid;//订单编号
    @BindView(R.id.createtime_tv)
    TextView createtimeTv;//下单时间
    @BindView(R.id.paytime_tv)
    TextView paytimeTv;//支付时间
    @BindView(R.id.order_cancel)
    TextView orderCancel;
    @BindView(R.id.order_sure)
    TextView orderSure;
    @BindView(R.id.order_delete)
    TextView orderDelete;
    @BindView(R.id.order_pay)
    TextView orderPay;
    @BindView(R.id.order_again)
    TextView orderAgain;
    @BindView(R.id.order_delay)
    TextView delay_order;//延长收货
    @BindView(R.id.order_comment)
    TextView order_comment;//评价
    @BindView(R.id.ll_pay)
    LinearLayout llPay;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.get_address)
    LinearLayout get_address;//配送地址显示
    private String orderId;
    private int states;//订单状态
    Timer timer = null;
    long createTime = 0;

    //取票人
    @BindView(R.id.ll_get_person)
    LinearLayout ll_get_person;
    @BindView(R.id.tv_collection_name)
    TextView tv_collection_name;
    @BindView(R.id.tv_collection_phone)
    TextView tv_collection_phone;

    List<DictBean.ReturnData> dictList = new ArrayList<>();
    private OrderListBean.OrderData orderBean;

    @NonNull
    @Override
    public OrderDetailPre createPresenter() {
        return new OrderDetailPre();
    }

    @Override
    protected String setTitle() {
        return getResources().getString(R.string.detail_pay);
    }

    @Override
    protected void showBack(TextView button_goback) {
        button_goback.setVisibility(View.VISIBLE);
        button_goback.setTypeface(iconfont);
        button_goback.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        button_goback.setTextColor(getResources().getColor(R.color.main_color));
        button_goback.setText(getResources().getString(R.string.back_normal) + getResources().getString(R.string.back));
    }

    @NonNull
    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initEvent() {
        tv_default.setTypeface(iconfont);
        orderId = getIntent().getStringExtra("orderId");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        getPresenter().getDict();
        getPresenter().getOrderDetail(orderId);
    }


    //获取订单交易的详情
    @Override
    public void setOrderDetailData(OrderDeatilBean orderBean) {
        if (orderBean.getReturnData() == null) {
            return;
        }
        setDetailData(orderBean.getReturnData());
    }

    private void setDetailData(OrderListBean.OrderData orderData) {
        orderBean=orderData;
        states = orderData.getState();
        createTime = orderData.getCtime();
        //判断订单状态  0 未支付 1 已支付 2 待发货 3 待收货 4 待评价（已收货） 5 已完成（已评价） 6 退款申请中 7 已退款 8交易关闭
        switch (states) {
            case 0:
                detail_iv.setImageResource(R.mipmap.icon_wait_pay);
                //设置时间倒计时
                setUpTimer(orderTime);
                orderState.setText("等待买家付款");
                orderPay.setVisibility(View.VISIBLE);
                orderCancel.setVisibility(View.VISIBLE);
                //不显示支付时间
                llPay.setVisibility(View.GONE);
                paytimeTv.setVisibility(View.GONE);
                break;
            case 1:
                detail_iv.setImageResource(R.mipmap.order_detail_send);
                orderState.setText("等待卖家发票");
                break;
            case 2:
                detail_iv.setImageResource(R.mipmap.order_detail_send);
                orderState.setText("等待卖家发票");
                break;
            case 3:
                detail_iv.setImageResource(R.mipmap.order_detail_pass);
                orderState.setText("卖家已发票");
                orderSure.setVisibility(View.VISIBLE);
                delay_order.setVisibility(View.VISIBLE);
                break;
            case 4:
                detail_iv.setImageResource(R.mipmap.icon_wait_pay);
                orderState.setText("待评价");
                order_comment.setVisibility(View.VISIBLE);
                break;
            case 5:
                detail_iv.setImageResource(R.mipmap.icon_wait_pay);
                orderState.setText("已完成");
                orderAgain.setVisibility(View.VISIBLE);
                break;
            case 6:
                detail_iv.setImageResource(R.mipmap.icon_wait_pay);
                orderState.setText("退款申请中");
                break;
            case 7:
                detail_iv.setImageResource(R.mipmap.icon_wait_pay);
                orderState.setText("已退款");
                break;
            case 8:
                detail_iv.setImageResource(R.mipmap.order_detail_close);
                orderDelete.setVisibility(View.VISIBLE);
                orderState.setText("交易关闭");
                llBottom.setVisibility(View.VISIBLE);
                //不显示支付时间
                llPay.setVisibility(View.GONE);
                paytimeTv.setVisibility(View.GONE);
                break;
        }
        list.clear();
        //处理价格相同的归类
        List<OrderListBean.OrderGoods> goodsList=orderData.getOrderGoodsTickets();
        Map<String,List<OrderListBean.OrderGoods>> orderMap=sortAmountList(goodsList);
        orderData.setOrderList(orderMap);
        //如果需要再次对分组后的数据进行操作,可以取出对应的数据
        Set<String> keySet = orderMap.keySet();
        List<OrderListBean.OrderGoods> goodsList1=new ArrayList<>();
        for(String groupName : keySet) {
            OrderListBean.OrderGoods ticketJson1 = new OrderListBean.OrderGoods();
            ticketJson1.setAmount(Float.parseFloat(groupName));
            ticketJson1.setNum(orderMap.get(groupName).size());
            String stringType="";
            for(OrderListBean.OrderGoods seatBean:orderMap.get(groupName)){
                stringType +=seatBean.getGoodsTicketName()+"、";
            }
            ticketJson1.setGoodsTicketName(stringType.substring(0,stringType.length()-1));
            goodsList1.add(ticketJson1);
        }
        orderData.setOrderGoodsTickets(goodsList1);
        list.addAll(orderData.getOrderGoodsTickets());
        adapter = new OrderDetailAdapter(this, orderData);
        recyclerView.setAdapter(adapter);
        adapter.setData(list);
        //票价总额
        totalTv.setText("¥" + orderData.getTotalTicketAmount());
        //优惠券
        couponTv.setText("-¥" + orderData.getCouponsAmount());
        if(orderData.getCouponsAmount()>0){
            lay_coupon.setVisibility(View.VISIBLE);
        }
        //快递费
        passTv.setText("¥" + orderData.getFreightAmount());
        if(orderData.getFreightAmount()>0){
            lay_send.setVisibility(View.VISIBLE);
        }
        //实付款
        tvAllmoney.setText("¥" + orderData.getPayAmount());
        //订单编号
        tvOrderid.setText("" + orderData.getOrderId());
        //下单时间
        createtimeTv.setText(Util.getTime(orderData.getCtime()*1000));
        //支付时间
        paytimeTv.setText(Util.getTime(orderData.getPayTime()*1000));
        String value = "";
        for (int i = 0; i < dictList.size(); i++) {
            if (dictList.get(i).getDicKey().equals(orderData.getCoolectTicketType()+"")) {
                value = dictList.get(i).getValue();
            }
        }


        if (value.contains("快递")) {//判断配送方式(快递配送)
            get_address.setVisibility(View.VISIBLE);
            ll_get_person.setVisibility(View.GONE);
            getPresenter().getOrderDetailAddress(orderId);
        } else if (value.contains("自取")) {//自取
            get_address.setVisibility(View.GONE);
            ll_get_person.setVisibility(View.VISIBLE);
        } else {
            get_address.setVisibility(View.GONE);
            ll_get_person.setVisibility(View.GONE);
        }
        if(orderData.getCollectName()!=null &&orderData.getCollectPhone()!=null){//显示取票人姓名以及取票人手机号
            tv_collection_name.setText(orderData.getCollectName());
            tv_collection_phone.setText(orderData.getCollectPhone());
        }

//        if (orderData.getCourierNo() != null && !orderData.getCourierNo().equals("")) {
//            getPresenter().getOrderSend(orderData.getCourierNo());
//        }
    }

    public void setUpTimer(final TextView textView) {
        if (timer == null) {
            TimerTask task = new TimerTask() {
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = textView;
                    mTimeHandler.sendMessage(message);
                }
            };
            timer = new Timer(true);
            timer.schedule(task, 0, 1000);
        }
    }

    private Handler mTimeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                TextView time_tv = (TextView) msg.obj;
                int time = (int) (900 - (Util.getTimeStamp() - createTime));
                String mm = time / 60 + "";
                String ss = time % 60 + "";
                if (time < 0) {
                    timer.cancel();
                    timer = null;
                    return;
                }
                time_tv.setText("" + (Integer.parseInt(mm) < 10 ? "0" + mm : mm) + ":" + (Integer.parseInt(ss) < 10 ? "0" + ss : ss));
            }
        }
    };

    //获取订单交易的收货地址
    @Override
    public void setOrderDetailAddress(AddressBean address) {
        if (address.returnCode.equals("0000")) {
            orderName.setText(address.getReturnData().getName());
            orderPhone.setText(address.getReturnData().getPhone());
            orderAddress.setText(address.getReturnData().getProvince()+address.getReturnData().getCity()+
                    address.getReturnData().getDistrict()+address.getReturnData().getDetailedAddress());
        }
    }

    //获取订单交易的快递信息
    @Override
    public void setOrderSend(SendDetailBean send) {

    }

    @OnClick({R.id.order_cancel, R.id.order_sure, R.id.order_delete, R.id.order_pay, R.id.order_again,R.id.order_comment,R.id.order_delay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.order_cancel://订单取消
                getPresenter().deleteCancel(this, orderId);
                break;
            case R.id.order_sure://确认收货的调用
                getPresenter().sureBtn(this, orderId);
                break;
            case R.id.order_delete://订单删除
                getPresenter().deleteBtn(this, orderId);
                break;
            case R.id.order_pay:
                getPresenter().setPayNow(this,iconfont,orderId);
                break;
            case R.id.order_again://再次购买
                Intent intent = new Intent(this, DetailTicketActivity.class);
                intent.putExtra("getId", "" + orderBean.getGoodsId());
                startActivity(intent);
                break;
            case R.id.order_comment://评价的操作
                getPresenter().setStarComment(this,orderId);
                break;
            case R.id.order_delay://延迟收货的操作
                getPresenter().setDelayOrder(this,orderId);
                break;
        }
    }

    /**
     * 确认收货的调用
     *
     * @param baseJSON
     */
    @Override
    public void setOrderSure(BaseJSON baseJSON) {
        if (baseJSON.returnMessage.equals("订单删除")) {
            ToastUtil.getToastEmail().ToastShow(this, null, 1, R.layout.toast_view, getResources().getString(R.string.delete_success));
            setResult(2003);
            finish();
        } else if (baseJSON.returnMessage.equals("订单取消")) {
            ToastUtil.getToastEmail().ToastShow(this, null, 1, R.layout.toast_view, getResources().getString(R.string.cancel) + getResources().getString(R.string.success_txt));
            Intent intent=new Intent(this,ResultPayActivity.class);
            intent.putExtra("orderStatus","1");
            startActivity(intent);
            setResult(2003);
            getPresenter().getOrderDetail(orderId);
            finish();
        } else if (baseJSON.returnMessage.equals("确认收货")) {
            ToastUtil.getToastEmail().ToastShow(this, null, 1, R.layout.toast_view, getResources().getString(R.string.received_success));
            Intent intent=new Intent(this,ResultPayActivity.class);
            intent.putExtra("orderStatus","2");
            startActivity(intent);
            setResult(2003);
            getPresenter().getOrderDetail(orderId);
        }  else if (baseJSON.returnMessage.equals("评分成功")) {
            ToastUtil.getToastEmail().ToastShow(this, null, 1, R.layout.toast_view, getResources().getString(R.string.comment_order) + getResources().getString(R.string.success_txt));
            setResult(2003);
            getPresenter().getOrderDetail(orderId);
        } else {
            RxToast.info(baseJSON.returnMessage);
        }
    }

    @Override
    public void showDict(DictBean bean) {
        if (bean.returnCode.equals("0000")) {
            dictList.clear();
            dictList.addAll(bean.getReturnData());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
    /**
     * 微信支付的回调
     * @param result
     */
    @Subscribe
    public void onEvent(SetBeanPay result) {
        Log.e("支付的回调",result.getMessage());
        if (result.getMessage().equals("支付成功") && result.getCodeData()== Constants.wxSuccess) {
            getIntent(ResultPayActivity.class);
            setResult(2003);
            finish();
        } else if (result.getMessage().equals("支付失败")&& result.getCodeData()==Constants.wxFailure) {
            getPresenter().getOrderDetail(orderId);
        } else if (result.getMessage().equals("支付取消")&& result.getCodeData()==Constants.wxCancel) {
            getPresenter().getOrderDetail(orderId);
        }
    }

    /**
     * 根据价格分类数据
     * @param list
     * @return
     */
    public Map<String,List<OrderListBean.OrderGoods>>  sortAmountList(List<OrderListBean.OrderGoods> list){
        TreeMap tm=new TreeMap();
        for(int i=0;i<list.size();i++){
            OrderListBean.OrderGoods s=list.get(i);
            if(tm.containsKey(""+s.getAmount())){//根据价格分类
                List<OrderListBean.OrderGoods> l11=(List<OrderListBean.OrderGoods>)tm.get(""+s.getAmount());
                l11.add(s);
            }else{
                List<OrderListBean.OrderGoods> tem=new ArrayList<>();
                tem.add(s);
                tm.put(""+s.getAmount(), tem);
            }
        }
        return tm;
    }

}
